package com.yu.dv.strategy.metadata.impl;

import com.yu.dv.entity.TableInfo;
import com.yu.dv.strategy.metadata.MetadataTemplate;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class PostgreSQLMetadataStrategy extends MetadataTemplate {

    @Override
    protected String getCatalog(Connection connection){
        return null; // PostgreSQL主要使用schema
    }

    @Override
    protected String getSchema(Connection connection)  {
        try {
            return connection.getSchema();
        } catch (Exception e) {
            return "public"; // 默认schema
        }
    }

    @Override
    protected String[] getTableTypes() {
        return new String[]{"TABLE", "VIEW"};
    }

    @Override
    protected List<TableInfo> getTablesWithFallback(Connection connection, String catalog, String schema) throws Exception {
        List<TableInfo> tables = new ArrayList<>();

        String query = "SELECT table_name as TABLE_NAME, table_type as TABLE_TYPE, '' as REMARKS " +
                "FROM information_schema.tables " +
                "WHERE table_schema = 'public'";

        try (Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery(query)) {

            while (rs.next()) {
                String tableName = rs.getString("TABLE_NAME");
                String tableType = rs.getString("TABLE_TYPE");
                String remarks = rs.getString("REMARKS");

                TableInfo table = new TableInfo(tableName, tableType, remarks);
                tables.add(table);
            }
        }

        log.info("PostgreSQL备用方案获取到 {} 张表", tables.size());
        return tables;
    }
}